<?php

namespace app\admin\controller;

use app\model\CardModel;
use app\model\CompanyModel;
use support\Request;
use support\Response;
use Exception;
use app\model\Util;
use app\model\CardItemModel;
use app\model\CardUserModel;
use app\model\UserModel;

class CardController
{
    /**
     * 获取富利卡列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            $company_id = $request->get('company_id');
            $created_at = $request->get('created_at');
            
            $query = CardModel::query()
                ->orderBy('sort_by', 'desc')
                ->orderBy('id', 'desc');
            
            // 公司搜索条件
            if (!empty($company_id)) {
                $query->where('company_id', $company_id);
            }
            
            // 时间范围搜索条件
            if (!empty($created_at)) {
                $dates = explode(',', $created_at);
                if (count($dates) === 2 && !empty($dates[0]) && !empty($dates[1])) {
                    $start_time = strtotime($dates[0] . ' 00:00:00');
                    $end_time = strtotime($dates[1] . ' 23:59:59');
                    $query->whereBetween('created_at', [$start_time, $end_time]);
                }
            }
                
            $total = $query->count();
            $list = $query->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            foreach ($list as &$item) {
                $item['image_url'] = Util::pathToUrl($item->image);
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                $item['updated_at'] = date('Y-m-d H:i:s', $item->updated_at);

                $item['item_total'] = CardItemModel::where('card_id', $item->id)->count();

                // 获取公司名称
                if($item->type == 'company'){
                    $company = CompanyModel::where('id', $item->company_id)->first();
                    $item['company_name'] = $company ? $company->name : '';
                }else{
                    $item['company_name'] = '-';
                }

                $item['user_total'] = CardUserModel::where('card_id', $item->id)->count();
                $item['user_total_score'] = CardUserModel::where('card_id', $item->id)->sum('use_score');
                
            }
                
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 提交/创建富利卡
     * @param Request $request
     * @return Response
     */
    public function submit(Request $request): Response
    {
        try {
            $data = $request->post();
            
            if (empty($data['name'])) {
                throw new Exception('福利卡名称不能为空');
            }

            if (!isset($data['score']) || $data['score'] < 0) {
                throw new Exception('云豆数不能为空且必须大于等于0');
            }

            // 判断是新建还是编辑
            if (!empty($data['id'])) {
                $card = CardModel::find($data['id']);
                if (!$card) {
                    throw new Exception('福利卡不存在');
                }
            } else {
                $card = new CardModel();
            }

            $card->company_id = empty($data['company_id']) ? 0 : $data['company_id'];
            $card->name = $data['name'];
            $card->image = $data['image'];
            $card->sort_by = empty($data['sort_by']) ? 0 : $data['sort_by'];
            $card->score = $data['score'];
            $card->expired_days = empty($data['expired_days']) ? 0 : $data['expired_days'];
            $card->price = empty($data['price']) ? 0 : $data['price'];
            $card->total = empty($data['total']) ? 0 : $data['total'];
            $card->type = $data['type'];
            $card->updated_at = time();
            
            // 新建时设置创建时间
            if (empty($data['id'])) {
                $card->created_at = time();
            }
            
            if (!$card->save()) {
                throw new Exception(empty($data['id']) ? '添加失败' : '更新失败');
            }

            return json([
                'data' => $card,
                'msg' => empty($data['id']) ? '添加成功' : '更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 删除富利卡
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        try {
            $id = $request->post('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $card = CardModel::find($id);
            if (!$card) {
                throw new Exception('富利卡不存在');
            }

            if (!$card->delete()) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取富利卡绑定记录列表
     * @param Request $request
     * @return Response
     */
    public function bindRecords(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            $search = $request->get('search', '');
            
            $query = CardUserModel::query()
                ->leftJoin('user', 'card_user.user_id', '=', 'user.id')
                ->leftJoin('card', 'card_user.card_id', '=', 'card.id')
                ->leftJoin('card_item', 'card_user.card_item_id', '=', 'card_item.id')
                ->select([
                    'card_user.*',
                    'user.nickname as user_name',
                    'user.phone as user_phone',
                    'card.name as card_name',
                    'card_item.card_no',
                    'card_item.card_number'
                ]);
                
            // 搜索条件
            if (!empty($search)) {
                $query->where(function($q) use ($search) {
                    $q->where('card_item.card_no', 'like', "%{$search}%")
                      ->orWhere('user.phone', 'like', "%{$search}%")
                      ->orWhere('card.name', 'like', "%{$search}%");
                });
            }
                
            $total = $query->count();
            $list = $query->orderBy('card_user.created_at', 'desc')
                ->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            foreach ($list as &$item) {
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                $item['updated_at'] = date('Y-m-d H:i:s', $item->updated_at);
                $item['expired_at'] = $item->expired_at ? date('Y-m-d H:i:s', $item->expired_at) : '永不过期';
                $item['status_text'] = CardUserModel::getStatusText($item->status);
            }
                
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
}
